package com.atguigu.daijia.rules.service.impl;

import com.atguigu.daijia.model.form.rules.FeeRuleRequest;
import com.atguigu.daijia.model.form.rules.FeeRuleRequestForm;
import com.atguigu.daijia.model.vo.rules.FeeRuleResponse;
import com.atguigu.daijia.model.vo.rules.FeeRuleResponseVo;

import com.atguigu.daijia.rules.service.FeeRuleService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;

import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class FeeRuleServiceImpl implements FeeRuleService {

    @Resource
    private KieContainer kieContainer;

    @Override
    public FeeRuleResponseVo calculateOrderFee(FeeRuleRequestForm calculateOrderFeeForm) {
        // 1. 获取 drools会话连接
        KieSession session = kieContainer.newKieSession();
        // 2. 封装 feeRuleRequest 对象
        FeeRuleRequest feeRuleRequest = new FeeRuleRequest();
       feeRuleRequest.setDistance(calculateOrderFeeForm.getDistance());
       feeRuleRequest.setWaitMinute(calculateOrderFeeForm.getWaitMinute());
       feeRuleRequest.setStartTime(new SimpleDateFormat("HH:mm:ss").format(calculateOrderFeeForm.getStartTime()));
        // 3. 执行drools规则
        FeeRuleResponse feeRuleResponse = new FeeRuleResponse();
        // 设置 drools全局变量
        session.setGlobal("feeRuleResponse", feeRuleResponse);
        // 将 feeRuleRequest 放入drools工作区
        session.insert(feeRuleRequest);
        // 激活所有drools规则
        session.fireAllRules();
        // 关闭会话
        session.dispose();
        // 4. 封装返回对象
        FeeRuleResponseVo feeRuleResponseVo = new FeeRuleResponseVo();
        BeanUtils.copyProperties(feeRuleResponse,feeRuleResponseVo);
        return feeRuleResponseVo;
    }
}
